/**
 * 
 */
package pl.koziolekweb.translator.engine;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.Set;

import org.apache.log4j.Logger;

/**
 * @author koziolek
 * 
 * 
 */

// Info: $Id$
public class TranslatorServiceFactory {

	private Map<String, TranslatorService> services;

	private static TranslatorServiceFactory instance = new TranslatorServiceFactory();

	private Logger logger;

	/**
	 * Konstruktor fabryki. Konfiguruje fabrykę.
	 */
	private TranslatorServiceFactory() {
		services = new HashMap<String, TranslatorService>();
		if(logger == null){
			logger = Logger.getRootLogger();
		}
		loadServces(ServiceLoader.load(TranslatorService.class));
	}

	/**
	 * Return list of name of available services.
	 * 
	 * @return set of services names
	 */
	public Set<String> getServiceList() {
		return services.keySet();
	}

	/**
	 * Return translator service by name. If service does not exist then return
	 * "NULL Service". Null service name is "NULL Service" and all operations
	 * return <b>null</b>.
	 * 
	 * @param serviceName
	 *            name of service
	 * @return
	 */
	public TranslatorService getTranslatorService(final String serviceName) {
		TranslatorService translatorService = services.get(serviceName);
		if (translatorService == null) {
			translatorService = new NullService();
		}
		logger.debug("Wybrano: " + translatorService.getServiceName());
		return translatorService;
	}

	private void loadServces(
			final ServiceLoader<TranslatorService> serviceLoader) {
		logger.info("Loading translator services...");
		for (TranslatorService translatorService : serviceLoader) {
			services.put(translatorService.getServiceName(), translatorService);
			logger.info("Service " + translatorService.getServiceName()
					+ " loaded");
		}
		logger.info("All availale services loaded.");
	}

	public static TranslatorServiceFactory getFactory() {
		return TranslatorServiceFactory.instance;
	}

	private static class NullService implements TranslatorService {

		@Override
		public String getServiceName() {
			return "NULL Service";
		}

		@Override
		public String translate(final String text) throws Throwable {
			return null;
		}

		@Override
		public String translate(final String text, final Language from)
				throws Throwable {
			return null;
		}

		@Override
		public String translate(final String text, final Language from,
				final Language to) throws Throwable {
			return null;
		}

		@Override
		public List<Language> getSupportedLanguages() {
			return null;
		}
	};

}
